package com.semidata.trp.algorithm.run;

import java.lang.reflect.Method;

import com.semidata.rtd.core.log.Logger;
import com.semidata.rtd.engine.dynamic.DynamicClassLoader;
import com.semidata.rtd.engine.job.Job;
import com.semidata.rtd.engine.job.SyncTask;
import com.semidata.trp.algorithm.config.Config;
import com.semidata.trp.algorithm.job.AlgorithmJob;
import com.semidata.trp.algorithm.job.AlgorithmJobContext;
import com.semidata.trp.algorithm.request.StrategyContext;

public class TaskRun extends SyncTask{

	public TaskRun(Job job, long timeout) {
		super(job, timeout);
		
	}

	@Override
	public void run() throws Exception {
		System.out.println("run");
		AlgorithmJobContext context = ((AlgorithmJob)getJob()).getJobContext();
		try {
			Class<?> algorithm = context.getAlgorithm();
			Method method = algorithm.getDeclaredMethod("calculate",StrategyContext.class);
			long start = System.currentTimeMillis();
			double result = (double)method.invoke(null, context.getArgs());
			long end = System.currentTimeMillis();
			long time = end - start;
			if (time > Config.getConfig().getRunTimeout())
				throw new InterruptedException("run time too long");
			context.setResult(result);
		} catch(Exception e) {
			Logger.log("ERROR", "runtime error : " + e.getMessage());
			e.printStackTrace();
			throw e;
		}
		
	}

}
